package notes.java.concurrent;

import java.util.concurrent.CountDownLatch;

/**
 * 模拟所有子线程都执行完成后再执行主线程 countdownLatch计数，模拟子线程执行完成之后再执行主线程 这个也可以用future来实现
 * 
 * @author wangcs
 *
 */
public class T1_TestCountDownLatchWait {

	public static void testWait() throws InterruptedException {
		System.out.println("主线程开始！！！");
		// 计数2个线程
		final CountDownLatch latch = new CountDownLatch(2);

		// 线程1
		new Thread() {
			public void run() {
				try {
					System.out.println("线程一开始！！！");
					Thread.sleep(3000);
					System.out.println("线程一运行完！！！");

					// 计数1
					latch.countDown();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();

		// 线程2
		new Thread() {
			public void run() {
				try {
					System.out.println("线程二开始！！！");
					Thread.sleep(5000);
					System.out.println("线程二运行完！！！");

					// 计数1
					latch.countDown();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}.start();
		
		// 等待所有线程运行完
		latch.await();
		System.out.println("回主线程！！！");
	}
	
	public static void main(String[] args) throws InterruptedException {
		testWait();
	}
}